import React, { useState } from 'react';
import './index.css';

interface IProps {
  className: string;
  showItemCount: number;
  startNum: number;
  currentPage: number;
  onChange: Function;
}

const Pagination: React.FunctionComponent<IProps> = ({
  className,
  showItemCount,
  startNum,
  currentPage,
  onChange,
}) => {
  // 起始页码
  const [start, setStart] = useState<number>(startNum);

  const arr = new Array(showItemCount).fill(0);

  // 点击页码
  const ClickPage = (e: any, index: number) => {
    e.preventDefault();
    onChange(index);
  };

  // 点击上一页
  const ClickPrev = (e: any) => {
    e.preventDefault();
    setStart(start - 1 > 0 ? start - 1 : start);
    onChange(currentPage - 1 > 0 ? currentPage - 1 : currentPage);
  };

  // 点击下一页
  const ClickNext = (e: any) => {
    e.preventDefault();
    setStart(start + 1);
    onChange(currentPage + 1);
  };

  return (
    <div className={className + ' xmy-pagination'}>
      <ul>
        <li className="prev" key="prev" onClick={ClickPrev}>
          <a href="/prev">上一页</a>
        </li>
        {arr.map((item, index) => {
          // 如果当前页为1时，起始页不为1，将其设为1
          if (currentPage === 1 && start !== 1) {
            setStart(1);
          }
          return (
            <li
              className={start + index === currentPage ? 'current' : ''}
              key={index}
              onClick={(e) => ClickPage(e, start + index)}
            >
              <a href={'/' + index}>{start + index}</a>
            </li>
          );
        })}
        <li>
          <a href="/more" key="more" onClick={(e) => e.preventDefault()}>
            ...
          </a>
        </li>
        <li className="next" key="next" onClick={ClickNext}>
          <a href="/next">下一页</a>
        </li>
      </ul>
    </div>
  );
};

export default Pagination;
